import Vue from 'vue';
import VueRouter from 'vue-router';
import { _import } from '@/utils/common';

import Login from '../views/Login.vue';
import Home from '../views/Home.vue';
import Welcome from '../views/Welcome.vue';
import Users from '../views/user/Users.vue';
import Rights from '../views/power/Rights.vue';
import Roles from '../views/power/Roles.vue';
import Cate from '../views/goods/Cate.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
    ],
  },
  {
    path: '/404',
    name: '404',
    component: _import('error-page/404'),
    meta: {
      title: '404页面',
      icon: '',
      hasAuth: true,
      keepAlive: false,
    },
  },
  {
    path: '/401',
    name: '401',
    component: _import('error-page/401'),
    meta: {
      title: '401页面',
      icon: '',
      hasAuth: true,
      keepAlive: false,
    },
  },
  {
    path: '*',
    redirect: '/404',
  },
];

const router = new VueRouter({
  mode: 'hash',
  routes,
});

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to表示将要访问的路径
  // from表示从哪个路径跳转而来
  // next是一个函数，它表示放行，它有两种调用方式：1.next() => 放行；2.next('/login') => 强制跳转
  const whiteList = ['/login', '/404', '/401'];
  if (whiteList.includes(to.path)) return next();
  const tokenStr = sessionStorage.getItem('token');
  if (!tokenStr) return next('/login');
  next();
});

export default router;
